/*
 * Project: Set Sample
 * Copyright (C) 2013 alf.labs gmail com,
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.alflabs.setsample.ui;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import com.alflabs.annotations.NonNull;
import com.alflabs.annotations.Null;
import com.alflabs.setsample.R;
import com.alflabs.setsample.core.GlobalContext;
import com.alflabs.setsample.core.SetPrefsValues;
import com.alflabs.setsample.stats.SetLevel;
import com.alflabs.setsample.stats.SetStats;

public class SetStatsFragment extends Fragment {

    private CheckBox mCheckTimesPerSol;

    @Override
    public void onCreate(Bundle state) {
        super.onCreate(state);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle state) {
        final View root = inflater.inflate(R.layout.set_stats_fragment, container, false);

        assert root != null;

        final ViewGroup table = (ViewGroup) root.findViewById(R.id.tableStats);

        final SetPrefsValues pv = new SetPrefsValues(getActivity());
        mCheckTimesPerSol = (CheckBox) root.findViewById(R.id.chkTimesPerSol);
        mCheckTimesPerSol.setChecked(pv.isStatsTimePerSol());
        mCheckTimesPerSol.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                updateTable(table);
                pv.setStatsTimePerSol(b);
            }
        });

        final SetStats s = GlobalContext.getInstance().getModel().getStats();
        assert s != null;
        //noinspection ConstantConditions
        if (s != null) {
            AsyncTask<Void, Void, Void> a = new AsyncTask<Void, Void, Void>() {
                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                    s.beginLoadAsync(getActivity());
                }

                @Override
                protected Void doInBackground(Void... voids) {
                    s.endLoadAsync();
                    return null;
                }

                @Override
                protected void onPostExecute(Void aVoid) {
                    super.onPostExecute(aVoid);
                    setupStatsTable(table, s);
                }
            };
            a.execute();
        }

        return root;
    }

    private void setupStatsTable(@Null ViewGroup table, @NonNull SetStats stats) {
        if (table == null) return;

        LayoutInflater inflater = getActivity().getLayoutInflater();
        final StringBuilder sb = new StringBuilder();

        for (int i = 0; i < 100; i++) {
            SetLevel tl = stats.getLevel(i);
            if (tl == null) break;
            int lvl = tl.getLevel();
            if (lvl < 1) continue; // should never happen

            View t = inflater.inflate(R.layout.set_stats_line, table, true);
            assert t == table;

            int n = table.getChildCount();
            if (n < 2) continue;

            View row = table.getChildAt(n - 1);
            assert row != null;

            setText(row, R.id.textNumSolutions, Integer.toString(lvl));
            setText(row, R.id.textNumGames, Integer.toString(tl.getGamesCompleted()));

            final int lvl1 = lvl;
            if (mCheckTimesPerSol != null && !mCheckTimesPerSol.isChecked()) {
                lvl = 1;
            }
            final long fastest = tl.getFastestTimeMs();
            final long avg = tl.getAvgTimeMs();

            final View v1 = setText(row, R.id.textFastestTime, SetBoardFragment.formatTime(sb, fastest / lvl, false));
            v1.setTag(new Runnable() {
                @Override
                public void run() {
                    int lvl2 = (mCheckTimesPerSol != null && !mCheckTimesPerSol.isChecked()) ? 1 : lvl1;
                    if (v1 instanceof TextView) {
                        ((TextView) v1).setText(SetBoardFragment.formatTime(sb, fastest / lvl2, false));
                    }
                }
            });

            final View v2 = setText(row, R.id.textAvgTime, SetBoardFragment.formatTime(sb, avg / lvl, false));
            v2.setTag(new Runnable() {
                @Override
                public void run() {
                    int lvl2 = (mCheckTimesPerSol != null && !mCheckTimesPerSol.isChecked()) ? 1 : lvl1;
                    if (v2 instanceof TextView) {
                        ((TextView) v2).setText(SetBoardFragment.formatTime(sb, avg / lvl2, false));
                    }
                }
            });
        }
    }

    private void updateTable(ViewGroup table) {
        if (table == null) return;
        int nrows = table.getChildCount();
        for (int i = 0; i < nrows; i++) {
            View row = table.getChildAt(i);
            if (row instanceof ViewGroup) {
                int ncols = ((ViewGroup) row).getChildCount();
                for (int j = 0; j < ncols; j++) {
                    View col = ((ViewGroup) row).getChildAt(j);
                    assert col != null;
                    Object tag = col.getTag();
                    if (tag instanceof Runnable) {
                        ((Runnable) tag).run();
                    }
                }
            }
        }
    }


    private View setText(@NonNull View root, int textId, @NonNull String value) {
        View v = root.findViewById(textId);
        if (v instanceof TextView) {
            ((TextView) v).setText(value);
        }
        return v;
    }

}
